package com.zipking.cloud.springbootmybatis.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class PropertiesListenerConfig implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {
    private static final Logger logger = LoggerFactory.getLogger(PropertiesListenerConfig.class);
    private static final ArrayList<String> propertyFileNames = new ArrayList<>();
    private static String env = "config/dev";
  /*  private Boolean initStatus;

    public PropertiesListenerConfig() {
        initStatus = Boolean.FALSE;
    }
*/
    public PropertiesListenerConfig(String[] propertyFileName) {
        propertyFileNames.addAll(Arrays.asList(propertyFileName));
    }

    @Override
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent applicationEnvironmentPreparedEvent) {
        // 读取配置环境
        if (StringUtils.hasText(applicationEnvironmentPreparedEvent.getEnvironment().getActiveProfiles()[0])) {
            env = applicationEnvironmentPreparedEvent.getEnvironment().getActiveProfiles()[0];
        }
        // 加载配置文件
        if (propertyFileNames.size() > 0) {
            for (String propertyFileName : propertyFileNames) {
                // 配置需要载入的配置文件
                PropertiesListenerConfig.loadAllProperties(propertyFileName);
            }
        }
    }


    public static Map<String, String> propertiesMap = null;

    private static void processProperties(Properties props) throws BeansException {
        if (propertiesMap == null) {
            propertiesMap = new HashMap<>();
        }
        for (Object key : props.keySet()) {
            String keyStr = key.toString();
            try {
                // PropertiesLoaderUtils的默认编码是ISO-8859-1,在这里转码一下
                propertiesMap.put(keyStr, new String(props.getProperty(keyStr).getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void loadAllProperties(String propertyFileName) {
        try {
            Properties properties = PropertiesLoaderUtils.loadAllProperties(getEnvPropPath(propertyFileName));
            processProperties(properties);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据配置文件名,获取系统环境下的配置文件
     *
     * @param propertyFileName 配置文件名称
     * @return 系统环境下的配置文件
     */
    public static Properties getEnvPropFile(String propertyFileName) {
        Properties properties = new Properties();
        try {
            properties.load(PropertyValues.class.getClassLoader().getResourceAsStream(getEnvPropPath(propertyFileName)));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return properties;
    }

    public static String getProperty(String name) {
        return propertiesMap.get(name);
    }

    public static Map<String, String> getAllProperty() {
        return propertiesMap;
    }

    /**
     * 根据配置文件名,获取系统环境下的配置文件路径
     *
     * @param propertyFileName 配置文件名称
     * @return 系统环境下的配置文件路径
     */
    private static String getEnvPropPath(String propertyFileName) {
        return "config/" + env + "/" + propertyFileName;
    }

}

